from rest_framework import serializers
from .models import ZtRdEfficiency
import json

#研发效能序列化
class ZtRdEfficiencySerializer(serializers.ModelSerializer):

    class Meta:
        model = ZtRdEfficiency
        fields = ['id', 'account', 'realname','positionType', 'dept', 'detail','score','positionRank','positionMaxRank', 'rank','maxRank', 'endDate', 'version']

    def get_translated_fields(self, obj):
        '''
        转换字段
        '''

        #转换关系
        positionType_map = {'develop': '开发',
                            'test': '测试',
                            'story': '需求',
                            'om': '运维',
                            'implement': '实施',
                            'ask': '综合/咨询'}

        # 定义一个字典，键是字段名，值是转换函数
        translations = {
            'positionType': lambda value: positionType_map[value],
            'detail': lambda value: json.loads(value)
        }

        # 获取原始值
        original_values = {field_name: obj[field_name] for field_name in translations}

        # 应用转换
        translated_values = {field_name: translations[field_name](original_value) for field_name, original_value in
                             original_values.items()}

        return translated_values

    def to_representation(self, instance):
        '''
        更新为转换后的值
        '''
        # 获取转换后的值
        translated_values = self.get_translated_fields(instance)

        # 将转换后的值添加到原始序列化器的数据中
        data = super(ZtRdEfficiencySerializer, self).to_representation(instance)
        data.update(translated_values)

        return data